package algorithm.util;

import org.junit.jupiter.api.Test;

/**
 * 给定四个整数 rows ,   cols ,  rCenter 和 cCenter 。有一个 rows x cols 的矩阵，你在单元格上的坐标是 (rCenter, cCenter) 。
 *
 * 返回矩阵中的所有单元格的坐标，并按与 (rCenter, cCenter) 的 距离 从最小到最大的顺序排。你可以按 任何 满足此条件的顺序返回答案。
 *
 * 单元格(r1, c1) 和 (r2, c2) 之间的距离为|r1 - r2| + |c1 - c2|。
 */
class Solution1030 {

    public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
        int[][] res = new int[cols * rows][2];

        int count = 0;
        int index = 1;
        boolean changed = true;
        int[] ints = isChanged(rows, cols, cCenter, rCenter, "F:");
        if (ints != null) {
            res[count++] = ints;
        } else {
            return res;
        }
        while (changed) {
            changed = false;

            int cornerRCenter = rCenter - index;
            int cornerCCenter = cCenter - index;
            for (int i = cornerRCenter + 1; i < cornerRCenter + 2 * index; i++) {
                //左边一列
                int x = cornerCCenter;
                ints = isChanged(rows, cols, x, i, "D:");
                if (ints != null) {
                    changed = true;
                    res[count++] = ints;
                }
                //右边一列
                x = cornerCCenter + 2 * index;
                ints = isChanged(rows, cols, x, i, "E:");
                if (ints != null) {
                    changed = true;
                    res[count++] = ints;
                }
            }
            for (int i = cornerCCenter; i < cols; i++) {
                //上边一行
                int y = cornerRCenter;
                ints = isChanged(rows, cols, i, y, "B:");
                if (ints != null) {
                    changed = true;
                    res[count++] = ints;
                }
                //下边一行
                y = cornerRCenter + 2 * index;
                ints = isChanged(rows, cols, i, y, "C:");
                if (ints != null) {
                    changed = true;
                    res[count++] = ints;
                }
            }


            index++;
        }

        return res;
    }

    private int[] isChanged(int rows, int cols, int x, int y, String s) {
        if (jump1(cols - 1, x)
                && jump1(rows - 1, y)
                && jump1(y, 0)
                && jump1(x, 0)) {
            System.out.println(s + (y) + "," + (x));
            return new int[]{y, x};
        }
        return null;
    }

    private boolean jump1(int center, int index) {
        return center >= index && index >= 0;
    }

    @Test
    public void add() {
        int[][] ints = allCellsDistOrder(2, 2, 0, 1);
        for (int[] a : ints) {
            System.out.println(a[0] + "," + a[1]);
        }
    }

}